<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'面试批次'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-date-picker v-model="listQuery.batch_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" class="filter-item"></el-date-picker>
      <el-select v-model="listQuery.group" placeholder="组别" class="filter-item" clearable>
        <el-option label="A" value="A"></el-option>
        <el-option label="B" value="B"></el-option>
        <el-option label="C" value="C"></el-option>
        <el-option label="D" value="D"></el-option>
        <el-option label="E" value="E"></el-option>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-alert
        :closable="false"
        title="PS：面试前请将面试批次的面试官一栏信息补全！多个面试官请用中文 ”、“号隔开。如：马云、马化腾。"
        type="warning">
      </el-alert>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <!--<el-table-column :label="'序号'" prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'面试批次'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'面试时间'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.time_format }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'面试人数'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.hr_interview_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="面试岗位" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.hr_interview_jobs }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'面试组别'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.group }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'面试轮'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type_name }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column :label="'面试官'" align="center">-->
      <!--<template slot-scope="scope">-->
      <!--<el-input v-model="scope.row.interviewer" @blur="changeInterviewer(scope.row.interviewer, scope.row.id)"></el-input>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'面试官'" align="center">
        <template slot-scope="scope">
          <el-autocomplete
            v-model="scope.row.interviewer"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入面试官姓名"
            value-key="name_email"
            @select="handlerInterviewerSelect(scope.row.id, $event)"
          ></el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column :label="'创建时间'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'操作'" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button :disabled="scope.row.hr_interview_num===0" type="success" size="small" @click="showList(scope.row)">面试名单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList" />

    <el-dialog :title="dialogStatus==='create' ? '新建部门' : '编辑部门'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="'部门：'">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item :label="'负责人：'">
          <el-input v-model="temp.principal"/>
        </el-form-item>
        <el-form-item :label="'联系电话：'">
          <el-input v-model="temp.tel"/>
        </el-form-item>
        <el-form-item :label="'分机号：'">
          <el-input v-model="temp.tel_sub"/>
        </el-form-item>
        <el-form-item :label="'邮箱：'">
          <el-input v-model="temp.email"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import { getBatchList, changeInterviewer } from '@/api/batch'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { searchUserByName } from '@/api/user'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'BatchHr',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        batch_date: '',
        group: undefined
      },
      queryString: '',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        principal: '',
        tel: '',
        tel_sub: '',
        email: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getBatchList(this.listQuery.page, { type: 3 }, this.queryString).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      const batch_date = this.listQuery.batch_date
      const group = this.listQuery.group
      if (name) {
        query += `name=${name}&`
      }
      if (batch_date) {
        query += `batch_date=${batch_date}&`
      }
      if (group) {
        query += `group=${group}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        principal: '',
        tel: '',
        tel_sub: '',
        email: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    changeInterviewer(val, id) {
      if (val === '') {
        return
      }
      changeInterviewer(id, val).then(response => {
        this.$message.success('修改成功')
      })
    },
    showList(row) {
      this.$router.push({
        name: 'hr-batch-list',
        query: { id: row.id }
      })
    },
    querySearchAsync(queryString, cb) {
      if (queryString !== '') {
        searchUserByName(queryString).then(res => {
          cb(res.data.data)
        })
      }
    },
    handlerInterviewerSelect(id, val) {
      changeInterviewer(id, val.name_email).then(response => {
        this.$message.success('修改成功')
      })
    }
  }
}
</script>
